package com.yc.security.config;

import com.yc.security.authentication.*;
import com.yc.security.authorize.JwtRequestFilter;
import com.yc.security.authorize.RedisRequestFilter;
import com.yc.security.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author kukaha
 * @version 1.0.0
 * @Configuration 配置类 @EnableWebSecurity 开启springSecurity过滤链filter
 * EnableGlobalMethodSecurity开启注解权限控制
 * @ClassName SpringSecurityConfig.java
 * @Description springSecurity配置类  实现安全控制
 * @createTime 2021年03月26日 20:05:00
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtAuthenticationAccessDenied jwtAuthenticationAccessDenied;

    @Autowired
    private UserDetailsService jwtUserDetailsServiceImpl;

//    @Autowired
//    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    private RedisRequestFilter redisRequestFilter;


    @Value("${jwt.route.authentication.path}")
    private String authenticationPath;


    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 认证管理器：
     * 1、认证信息提供方式（用户名、密码、当前用户的资源权限）
     * 2、可采用内存存储方式，也可能采用数据库方式等
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsServiceImpl);
//        auth.userDetailsService(jwtUserDetailsServiceImpl).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 将认证管理器添加到spring容器中
     *
     * @title
     * @author kukaha
     * @updateTime 22:47
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        System.out.println("authenticationPath:" + authenticationPath);
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                .exceptionHandling()
                //设置未登录异常处理器
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                //设置无权限访问异常处理器
                .accessDeniedHandler(jwtAuthenticationAccessDenied)
                //管理session
                .and().sessionManagement()
                //将session策略设置为无状态 也就是不适应session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //设置匹配到的路径不进行拦截
                .antMatchers(authenticationPath).permitAll()
                .anyRequest().authenticated()
                .and()
                //添加请求过滤器对请求进行拦截,验证是否满足条件
                .addFilterBefore(redisRequestFilter, UsernamePasswordAuthenticationFilter.class);

        // disable page caching
        httpSecurity
                .headers()
                .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
                .cacheControl();
    }

    /**
     * // AuthenticationTokenFilter will ignore the below paths
     * 认证过滤将忽略下面配置的路径
     * 释放资源
     *
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {

        web
                .ignoring()
                .antMatchers(
                        HttpMethod.POST,
                        securityProperties.getAuthentication().getUrlDischarged()
                )

                // allow anonymous resource requests
                .and()
                .ignoring()
                .antMatchers(
                        HttpMethod.GET,
                        securityProperties.getAuthentication().getStaticPaths()
                );
    }

}
